package cn.wangdh.domain.activity.service;

import cn.wangdh.domain.activity.model.aggregate.CreateOrderAggregate;
import cn.wangdh.domain.activity.model.entity.ActivityCountEntity;
import cn.wangdh.domain.activity.model.entity.ActivityEntity;
import cn.wangdh.domain.activity.model.entity.ActivitySkuEntity;
import cn.wangdh.domain.activity.model.entity.SkuRechargeEntity;
import cn.wangdh.domain.activity.respository.IActivityRepository;
import cn.wangdh.domain.activity.service.rule.IActionChain;
import cn.wangdh.domain.activity.service.rule.factory.DefaultActivityChainFactory;
import cn.wangdh.types.enums.ResponseCode;
import cn.wangdh.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author WDH
 * @description 抽奖活动抽象类，定义标准的流程
 * @date 2024年11月18日 14:51
 */

@Slf4j
public abstract class AbstractRaffleActivity extends RaffleActivitySupport implements IRaffleOrder {


    public AbstractRaffleActivity(DefaultActivityChainFactory defaultActivityChainFactory, IActivityRepository activityRepository) {
        super(defaultActivityChainFactory, activityRepository);
    }



    @Override
    public String createSkuRechargeOrder(SkuRechargeEntity skuRechargeEntity) {
//        1.参数校验
        String userId = skuRechargeEntity.getUserId();
        Long sku = skuRechargeEntity.getSku();
        String outBusinessNo = skuRechargeEntity.getOutBusinessNo();
        if (sku == null || StringUtils.isBlank(userId) || StringUtils.isBlank(outBusinessNo)) {
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
//        2.查询基础信息
//        2.1通过sku查询活动信息
        ActivitySkuEntity activitySkuEntity = queryActivitySku(sku);
//2.2查询活动信息
        ActivityEntity activityEntity = queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());
//        2.3查询用户可参与次数
        ActivityCountEntity activityCountEntity = queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
//3.活动动作规则校验
        IActionChain actionChain = defaultActivityChainFactory.openActionChain();
        boolean success = actionChain.action(activitySkuEntity, activityEntity, activityCountEntity);
//        4.构建聚合对象
        CreateOrderAggregate createOrderAggregate = buildOrderAggregate(skuRechargeEntity, activitySkuEntity, activityEntity, activityCountEntity);
//        5.保存订单
        doSaveOrder(createOrderAggregate);

        return createOrderAggregate.getActivityOrderEntity().getOrderId();
    }

    protected abstract void doSaveOrder(CreateOrderAggregate createOrderAggregate);

    protected abstract CreateOrderAggregate buildOrderAggregate(SkuRechargeEntity skuRechargeEntity, ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity);
}
